import java.util.LinkedList;
import java.util.Queue;

public class demo1 {
    int[]dx={0,0,1,-1};
    int[]dy={1,-1,0,0};
    int m;
    int n;
    boolean[][]arr;
    public int nearestExit(char[][] maze, int[] entrance) {
        m=maze.length;
        n=maze[0].length;
        arr=new boolean[m][n];
        return BFS(maze,entrance[0],entrance[1]);
    }
    public int BFS(char[][] maze,int x,int y){
        Queue<int[]>queue=new LinkedList<>();
        queue.add(new int[]{x,y});
        int sum=0;
        while (!queue.isEmpty()){
            sum++;
            int size=queue.size();
            for (int i = 0; i <size ; i++) {
                int[] ret = queue.poll();
                int a=ret[0];
                int b=ret[1];
                arr[a][b]=true;
                for (int j = 0; j <4 ; j++) {
                    int c=a+dx[j];
                    int d=b+dy[j];
                    if(c==m-1||c==0||d==0||d==n-1)return sum;
                    if(c>=0&&c<m&&d>=0&&d<n&&maze[c][d]=='.'&&!arr[c][d]){
                        queue.add(new int[]{c,d});
                    }
                }
            }
        }
        return sum;
    }
}
